package com.key.w8.common;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: k8
 * @CreateTime: 2025-03-23
 * @Version: 1.0
 */
public class NamedThreadFactory implements ThreadFactory {
    private final String prefix;
    private final ThreadGroup group;
    private final AtomicInteger threadNumber;
    private final boolean isDaemon;
    private final Thread.UncaughtExceptionHandler handler;
    public static NamedThreadFactory DAEMON_THREAD_FACTORY = new NamedThreadFactory("k8remoting", true);
    public static NamedThreadFactory USER_THREAD_FACTORY = new NamedThreadFactory("k8remoting", false);

    public NamedThreadFactory(String prefix, boolean isDaemon) {
        this(prefix, (ThreadGroup)null, isDaemon);
    }

    public NamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon) {
        this(prefix, threadGroup, isDaemon, (Thread.UncaughtExceptionHandler)null);
    }

    public NamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon, Thread.UncaughtExceptionHandler handler) {
        this.threadNumber = new AtomicInteger(1);
        this.prefix = isBlank(prefix) ? "k8remoting" : prefix;
        if (null == threadGroup) {
            threadGroup = Thread.currentThread().getThreadGroup();
        }

        this.group = threadGroup;
        this.isDaemon = isDaemon;
        this.handler = handler;
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(this.group, r, format("{}{}", new String[]{this.prefix, String.valueOf(this.threadNumber.getAndIncrement())}));
        if (!t.isDaemon()) {
            if (this.isDaemon) {
                t.setDaemon(true);
            }
        } else if (!this.isDaemon) {
            t.setDaemon(false);
        }

        if (null != this.handler) {
            t.setUncaughtExceptionHandler(this.handler);
        }

        if (5 != t.getPriority()) {
            t.setPriority(5);
        }

        return t;
    }
    public static boolean isBlank(String str) {
        if (str == null) {
            return true;
        }
        int length = str.length();
        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static String format(String s, String[] strings) {
        String formattedTemplate = s.replace("{}", "%s");
        return String.format(formattedTemplate, strings);
    }
}
